import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';


import '../../theme/kq_theme_manager.dart';

///面包屑组件
class KqBreadCrumbs<T extends ICrumbs> extends StatefulWidget {
  final List<T> crumbs;
  final Color? colorParent;
  final Color? colorChild;
  final Function(int index, T item)? onTap;

  /// 字体大小
  final double? fontSize;

  const KqBreadCrumbs(
      {super.key,
      this.crumbs = const [],
      this.colorParent,
      this.colorChild = Colors.grey,
      this.fontSize,
      this.onTap});

  @override
  State<StatefulWidget> createState() => _KqBreadCrumbsState<T>();
}

class _KqBreadCrumbsState<T extends ICrumbs> extends State<KqBreadCrumbs<T>> {
  final ScrollController _scrollController = ScrollController();

  void _scrollToEnd() {
    _scrollController.animateTo(_scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 200), curve: Curves.ease);
  }

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _scrollToEnd();
    });
  }

  @override
  void didUpdateWidget(covariant KqBreadCrumbs<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    Timer.periodic(const Duration(milliseconds: 50), (timer) {
      if (mounted) {
        _scrollToEnd();
      }
      timer.cancel();
    });
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      child: SingleChildScrollView(
        controller: _scrollController,
        scrollDirection: Axis.horizontal,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: _getWidget(widget.crumbs),
        ),
      ),
    );
  }

  List<Widget> _getWidget(List<T> crumbs) {
    List<Widget> widgets = [];
    for (int i = 0; i < crumbs.length; i++) {
      Color? textColor;
      String? text;
      if (i < crumbs.length - 1) {
        textColor = widget.colorParent ??
            KqThemeManager.getCommonConfig().mainLightColor;
        text = "${crumbs[i].title}>";
      } else {
        textColor = widget.colorChild;
        text = crumbs[i].title;
      }
      widgets.add(InkWell(
        child: Text(
          text,
          style:
              TextStyle(color: textColor, fontSize: widget.fontSize ?? 14 ),
        ),
        onTap: () {
          if (i < widget.crumbs.length - 1) {
            widget.crumbs.removeRange(i + 1, widget.crumbs.length);
            setState(() {});
          }
          widget.onTap?.call(i, crumbs[i]);
        },
      ));
    }
    return widgets;
  }
}

class ICrumbs {
  final String title;

  ICrumbs(this.title);
}
